<?php

namespace App\Models\Notice;

use App\Models\BaseModel;

class NoticeRecord extends BaseModel
{

    protected $table = 'notice_records';
    protected $fillable = ['notice_id', 'user_id', 'is_readed','data_scope'];
    public $params = ['notice_id', 'is_readed'];
    public $sorters = ['title', 'is_readed', 'created_at'];

    public function notice()
    {
        return $this->belongsTo('App\Models\Notice\SystemNotice', 'notice_id', 'id');
    }

    //todo: 1,根据是否已读，通知标题查找,2,排序功能
    public function getMyNoticeList($user_id, $limit, $sorter, $search)
    {
        $perPage = $limit > 0 ? $limit : $this->limit;
        $noticeRecord = $this->with('notice:id,title,content')
                ->where('user_id', '=', $user_id)
                ->select(['id', 'notice_id', 'created_at', 'is_readed'])
                ->orderBy($sorter[0], $sorter[1])
                ->paginate($perPage);
        if ($noticeRecord) {
            return $noticeRecord->toArray();
        } else {
            return null;
        }
    }

    public function readNotice($userId, $noticeId)
    {
        $noticeRecord = $this->where(['user_id' => $userId, 'notice_id' => $noticeId])->first();
        if ($noticeRecord) {
            if ($noticeRecord->is_readed === 0) {
                return $noticeRecord->update(['is_readed' => 1]);
            }
        } else {
            return null;
        }
    }

}
